# -*- coding: utf-8 -*-
from . import BaseController
from backend.libs import myjson as json
from backend.models import Resource


class ResourceListController(BaseController):

    def get(self):
        r = Resource.objects
        resource_name = self.get_argument('ResourceName', '')
        if resource_name:
            r = r.filter(name__contains=resource_name)

        disabled = self.int_argument('disabled', 0)
        r = r.filter(disabled=disabled).order_by('show_order')
        
        number_per_page = self.int_argument('pageSize', 100)
        paginator = self.pagination(r.all(), number_per_page=number_per_page)

        return self.render_json(data=paginator)


class ResourceOptionsListController(BaseController):

    def get(self):
        res_in_db = Resource.objects.filter(disabled=0).order_by('parent_id').order_by('show_order').all()
        data = [ r.to_option_dict() for r in res_in_db ]
        return self.render_json(data=data)


class ResourceTreeController(BaseController):

    def get(self):
        resource_tree_data = Resource.to_tree()
        return self.render_json(data=resource_tree_data)


class CreateResourceController(BaseController):

    def post(self):
        data = json.loads(self.request.body)
        print(data)
        if not data['name']:
            return self.render_json(code=1001, msg='资源名称不能为空')
        resource_id = data['id']

        resource = Resource() if int(resource_id) <= 0 else Resource.objects.filter(id=resource_id).first()
        parent_id = data.get('parent_id', '0')
        if parent_id and int(parent_id) > 0:
            resource.parent_id = int(parent_id)
        resource.name = data['name']
        resource.description = data['description']
        resource.cate = data['cate']
        resource.permission = data['permission']
        resource.url = data['url']
        resource.icon = data['icon']
        resource.disabled = data['disabled']
        resource.show_order = data['show_order']
        resource.save()
        return self.render_json(data=resource.to_dict())


class DeleteResourceController(BaseController):

    def post(self, resource_id):
        """菜单删除功能使用软删除方式
        """
        resource_id = int(resource_id)
        if resource_id > 0:
            resource = Resource.objects.filter(id=resource_id).first()
            if resource:
                resource.disabled = 1
                resource.save()
                # resource.delete()

        return self.render_json()
